var app = getApp();
var ajax = require('../../utils/ajax.js');

Page({
  data: {
    dataLoaded: false,
    loading: false,
    moreLoading: false,
    currentTab: 0,
    orderList: [],
    page: 1,
    noMore: false,
  },

  onLoad: function (options) {
    var self = this;

    this._toTab(+options.ty || 0, function () {
      self.setData({
        dataLoaded: true
      });
    });
  },
  onShareAppMessage: function () {
    return {
      title: this.data.shop.shareTitle,
      path: "pages/index/index"
    }
  },
  /**
   * 事件切换tab
   */
  _tabSwitch: function (evt) {
    var index = +evt.currentTarget.dataset.current;

    this._toTab(index);
  },

  _toTab: function (index, cb) {
    this.setData({
      currentTab: index,
      orderList: [],
      page: 1,
      noMore: false,
    });
    this._getOrderList({ ty: index }, cb);
  },


  _getOrderList: function (params, cb) {
    var self = this;
    var ty = params.ty;
    var isMore = params.isMore;
    var page = self.data.page || 1;
    var url = '';

    switch (ty) {
      case 0:
        url = '/openapi/CHome/toPayOrderList';
        break;
      case 1:
        url = '/openapi/CHome/toDeliveryOrderList';
        break;
      case 2:
        url = '/openapi/CHome/toTakeDeliveryOrderList';
        break;
      case 3:
        url = '/openapi/CHome/finishedOrderList';
        break;
    }

    if (isMore) {
      self.setData({
        moreLoading: true
      });
    } else {
      self.setData({
        loading: true
      });
    }
    ajax.G(url, {
      page: page
    }, function (data) {
      var list = data.result.orderList || [];
      var toData = {
        orderList: list.concat(self.data.orderList),
        noMore: list.length == 0,
        page: self.data.page + 1,
      };
      toData[isMore ? 'moreLoading' : 'loading'] = false;
      self.setData(toData);
      cb && cb();
    });
  },

  /**
   * 加载更多
   */
  _loadMore: function () {
    console.log('---_loadMore')
    if (this.data.moreLoading || this.data.loading || this.data.noMore) {
      return;
    }
    this._getOrderList({
      ty: this.data.currentTab,
      isMore: true
    });
  },

});









